#!/usr/bin/env bash

PARENT_DIR=$1
if [ -z "$PARENT_DIR" ];
then
    PARENT_DIR=~/
fi
pushd "$PARENT_DIR" > /dev/null
PARENT_DIR=`pwd`
popd > /dev/null

TARGET_DIR=$2
if [ -z "$TARGET_DIR" ];
then
    TARGET_DIR=`dirname "$0"`/..
fi

pushd "$TARGET_DIR" > /dev/null
TARGET_DIR=`pwd`
popd > /dev/null

function link_to {
    local SOURCE_FILE=$1
    local LINK=$2
    local SOURCE_FILE_FULL=$TARGET_DIR/$SOURCE_FILE
    local LINK_FULL=$PARENT_DIR/$LINK

    if [ ! -e "$SOURCE_FILE_FULL" ];
    then
        return
    fi

    LINK_LINKED_TO=`readlink "$LINK_FULL" || true`

    if [ "$LINK_LINKED_TO" = "$SOURCE_FILE_FULL" ];
    then
        return
    fi

    if [ -e "$LINK_FULL" ];
    then
        LINK_FULL_MOVE=${LINK_FULL}.old
        echo "moving \"$LINK_FULL\" to \"$LINK_FULL_MOVE\""
        mv "$LINK_FULL" "$LINK_FULL_MOVE"
    fi

    LINK_DIR=`dirname $LINK`
    mkdir -p $LINK_DIR
    pushd "$PARENT_DIR" > /dev/null
    ln -s "$SOURCE_FILE_FULL" "$LINK"
    popd > /dev/null
}

TASKS='
gdb/.gdbinit	.gdbinit
vim/.vim	.vim
vim/.vimrc	.vimrc
vim/.gvimrc	.gvimrc
svn/config	.subversion/config
hg/.hgrc	.hgrc
ssh/config	.ssh/config
pentadactyl/.pentadactylrc	.pentadactylrc
bash/.inputrc	.inputrc
bash/.bash_profile	.bash_profile
pip/pip.conf	.pip/pip.conf
'


echo "$TASKS" |
while read -r TASK;
do
    if [ -z "$TASK" ];
    then
        continue
    fi

    SOURCE=`echo "$TASK" | cut -f 1`
    LINKNAME=`echo "$TASK" | cut -f 2`

    link_to "$SOURCE" "$LINKNAME"
done
